<template>  
  <div id="app">  
    <div class="container">  
      <div class="left-panel">  
        <div class="header">  
          <div v-for="note in tableData" :key="note.id" class="note-header">  
            <el-avatar  
              :src="'http://localhost:8080/images/upload/' + note.profile_picture"  
              class="avatar"  
              style="cursor: pointer;"  
              @click="opennotedetail(note)"  
            ></el-avatar>  
            <h2 class="username">{{ note.user_name }}</h2>  
          </div>  
          <div class="note-action">  
            <div class="action-buttons">  
              <el-button icon="Star" plain round @click="handlelike">{{ isCollected ? "已收藏笔记" : "收藏笔记" }}</el-button>  
              <el-button type="text" icon="Back" @click="$router.go(-1)" style="color: black;"></el-button>  
            </div>  
          </div>  
        </div>  

        <div v-for="note in tableData" :key="note.id" class="note-item">  
          <div class="title-tag-container">  
            <h1 class="title">{{ note.title }}</h1>&nbsp;&nbsp;&nbsp;
            <h3 class="tag">#{{ note.note_type }}</h3>  
          </div>  

          <div class="cover-image">  
            <img  
              :src="'http://localhost:8080/images/upload/' + note.image"  
              alt="note Cover"  
              class="note-cover"  
            />  
          </div>  
          <div class="content" style="overflow-y: auto; max-height: 200px;">{{ note.note_content }}</div>  

          <div class="info-bar">  
            <div class="timestamp">{{ formatDate(note.create_time) }}</div>  
            <div class="stats">
              <span><el-icon><View /></el-icon>&nbsp;{{ note.view_count }}</span>&nbsp;&nbsp;&nbsp;  
              <span><el-icon><ChatDotRound /></el-icon>&nbsp;{{ publishedCommentCount }}</span>&nbsp;&nbsp;&nbsp;  
              <span><el-icon><Star /></el-icon>&nbsp;{{ publishedNoteCount }}</span>  
            </div>  
          </div>  
        </div>  

        <div class="add-comment">  
          <el-input v-model="newComment" maxlength="50" show-word-limit  placeholder="期待你的评论！" clearable></el-input>&nbsp;&nbsp;  
          <button @click="submitComment">发送</button>  
        </div>  
      </div>  

      <div class="right-panel">  
        <div class="comments-container" style="overflow-y: auto; max-height: 600px;">  
       <div v-for="comment in tableData1" :key="comment.id" class="comment">  
       <div class="comment-info">  
        <div class="comment-header">  
        <el-avatar  
          :src="'http://localhost:8080/images/upload/' + comment.profile_picture"  
          class="comment-avatar"  
          style="cursor: pointer;"  
          @click="opennotedetail(comment)"  
        ></el-avatar>  
        <div class="comment-details">  
          <span class="comment-author">{{ comment.user_name }}</span>  
          <div class="comment-date">{{ formatDate(comment.create_time) }}</div>  
        </div>  
      </div>  
      <div class="comment-text">{{ comment.note_comment_content }}</div>  
    </div>  
    <div class="note-action">  
      <el-button  
        icon="Star"  
        plain  
        round  
        @click="handleLike(comment)"  
      >{{ comment.isLiked ? "已点赞" : "点赞" }}&nbsp;({{comment.likeCount}})</el-button>  
      <el-button icon="Warning" plain round @click="handleReport(comment.note_comment_id)">举报</el-button>  
    </div>  
  </div>  
</div>
      </div>  
    </div>  
  </div>  
</template>

<script>  
import { ElMessage, ElMessageBox } from 'element-plus';  
import axios from 'axios';  
export default {  
  data() {  
    return {  
      tableData: [], // 存储用户头像和用户名  
      tableData1: [],  
      newComment: '',  
      userId:'',  
      note_create_id:'',  
      publishedCommentCount: 0, // 初始化笔记评论数量  
      publishedNoteCount: 0,   // 初始化收藏数量  
      commentsText: '', 
      likeCount:0,
      isCollected:false,   //初始化为"收藏笔记"
    };  
  },  
  methods: {  
    //格式化日期
    formatDate(dateString) {  
      const date = new Date(dateString);  
      const year = date.getFullYear();  
      const month = String(date.getMonth() + 1      ).padStart(2, '0');  
      const day = String(date.getDate()).padStart(2, '0');  
      const hours = String(date.getHours()).padStart(2, '0');  
      const minutes = String(date.getMinutes()).padStart(2, '0');  
      return `${year}-${month}-${day} ${hours}:${minutes}`;  
    },  

    //路由跳转
    navigateTo(route) {  
      this.$router.push(route);  
    },  

     //进入他人主页页面
  opennotedetail(note){
    localStorage.setItem('user_id', this.userId);
   // sessionStorage.setItem('user_id', note.user_id);
    this.navigateTo('/HisHome/:user_id', note);
  },


    //从评论页进入到他人主页
    opennotedetail(comment) {  
      localStorage.setItem('user_id', this.userId);  
      this.navigateTo(`/HisHome/${comment.user_id}`);  // 使用 `user_id` 来构建路由  
    },  

    //获取笔记的评论数量
    fetchpublishedCommentCount() {  
      axios.get(`/v1/NoteComment/count`, {  
        params: { note_create_id: this.note_create_id }  
      }).then(response => {  
        this.publishedCommentCount = response.data;  
      });  
    },  

     //获取笔记的收藏数量
    fetchpublishedNoteCount() {  
      axios.get(`/v1/NoteCollectionnoteid/count`, {  
        params: { note_create_id: this.note_create_id }  
      }).then(response => {  
        this.publishedNoteCount = response.data;  
      });  
    },  

    //获取每条评论的点赞数量
    fetchpublishedlikeCount(comment){
      axios.get(`/likeNoteComment/count`, {  
        params: { note_comment_id: comment.note_comment_id }  
      }).then(response => {  
        comment.likeCount = response.data;  
      }); 
    },

    //获取用户名、头像、笔记相关内容信息
    getAllUser() {  
      this.$http.get("/v1/NoteCreateinfonoteid", {  
        params: { note_create_id: this.note_create_id }  
      }).then((response) => {  
        this.tableData = response.data.list;   
      });   
    },  
    
    //获取评论内容
    getNoteComment() {  
      this.$http.get("/v1/NoteCommentinfonoteid", {  
        params: { note_create_id: this.note_create_id }  
      }).then((response) => {  
        this.tableData1 = response.data.list.map(comment => ({
        ...comment,
        isLiked: false, // 初始化点赞状态   //在不修改原始对象：评论comment的情况下，创建一个新对象isLiked并添加或修改属性。
        likeCount:0     //初始化点赞数量
      }));  
      this.tableData1.forEach(comment => {   // 遍历评论，获取每条评论的点赞数量
        this.fetchpublishedlikeCount(comment);
      });
       this.checkIfCollected(); // 初始化时检查点赞状态 
      });   
    },  
    
    //举报
    handleReport(note_comment_id) {
    ElMessageBox.confirm(
    '您确定要举报本条评论吗?',
    '举报评论',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    }
  )
    .then(() => {
    axios.put(`/v1/NoteCommentStatus/${note_comment_id}`)  //修改状态（被举报）
      .then(response => {
        ElMessage.success('您的举报已收到，谢谢！');
        this.getNoteComment();
      })
      .catch(error => {
        if (axios.isCancel(error)) {
          console.log('Request canceled', error.message);
        } else {
          ElMessage.error('举报失败：' + error.message);
          console.error(error);
        }
      });
    }).catch(() => {
    // 处理用户取消逻辑
       ElMessage.info('举报已取消');
     });
    },

    // 检查是否已经点赞 forEach遍历tableData1数组中的每个评论
   checkIfCollected() {
   this.tableData1.forEach(comment => {
    axios
      .get(`/likeNoteComment/check`, {
        params: { user_id:this.userId, note_comment_id: comment.note_comment_id },
      })
      .then((response) => {
        comment.isLiked = response.data.like; // 设置每个评论的点赞状态
      })
      .catch((error) => {
        console.error("检查收藏状态失败：", error);
      });
  });
},

  // 点赞或取消点赞操作
  handleLike(comment) {
  const url = comment.isLiked ? `/likeNoteComment/delete` : `/likeNoteComment/add`;
  const data = { user_id:this.userId, note_comment_id: comment.note_comment_id };
  axios({
    method: comment.isLiked ? "delete" : "post", 
    url,
    data,
  })
  .then((response) => {
    if (response.data.success) {
      comment.isLiked = !comment.isLiked; // 切换单个评论的点赞状态
      this.fetchpublishedlikeCount(comment); // 重新获取点赞数量
      const message = comment.isLiked ? "点赞成功" : "取消点赞成功";
      ElMessage.success(message);
    } else {
      ElMessage.error("操作失败，请稍后再试！");
    }
  })
  .catch((error) => {
    console.error("收藏操作失败：", error);
    ElMessage.error("网络错误，请稍后重试！");
  });
},

   //检查是否已经收藏
   checkIfCollectedNote() {
    axios
      .get(`/v1/NoteCollectioncheck`, {
        params: { user_id:this.userId, note_create_id: this.note_create_id},
      })
      .then((response) => {
        this.isCollected = response.data.collected; // 设置每条的收藏状态
      })
      .catch((error) => {
        console.error("检查收藏状态失败：", error);
      });
},
  
    //收藏
    handlelike() {  
    const url = this.isCollected ? `/v1/NoteCollectiondelete` : `/v1/NoteCollectionadd`;
    const data = { user_id:this.userId, note_create_id: this.note_create_id };
    axios({
    method: this.isCollected ? "delete" : "post", 
    url,
    data,
  })
  .then((response) => {
    if (response.data.success) {
      this.isCollected = !this.isCollected; // 切换收藏状态
      this.fetchpublishedNoteCount();   //重新获取收藏笔记数量
      const message = this.isCollected ? "收藏成功" : "取消收藏成功";
      ElMessage.success(message);
    } else {
      ElMessage.error("操作失败，请稍后再试！");
    }
  })
  .catch((error) => {
    console.error("收藏操作失败：", error);
    ElMessage.error("网络错误，请稍后重试！");
  });
    },  
    

    //发送评论
    submitComment() {  
      if (this.newComment.trim() !== '') {  
        this.$http.post('/v1/NoteComment', {note_create_id: this.note_create_id, user_id:this.userId, note_comment_content: this.newComment, like_count: 0, comment_count: 0, status: "正常"})  
          .then(() => {  
            this.newComment = ''; // 清空输入框  
            ElMessage.success('评论成功！');  
            this.getNoteComment();
            this.fetchpublishedCommentCount();  
          })  
          .catch(error => {  
            ElMessage.error('评论失败，请重试！');  
            console.error(error);  
          });  
      }  
    },
  },  

  //mounted：在组件准备前获取数据，初始化数据且用于执行导航守卫之后的操作，确保在路由跳转后执行特定的逻辑。
  mounted() {  
    this.userId = localStorage.getItem('user_id');  
    this.note_create_id = sessionStorage.getItem('note_create_id') || localStorage.getItem('note_create_id');  
    this.getAllUser();        //获取用户、笔记相关信息
    this.getNoteComment();   //获取评论信息
    this.fetchpublishedCommentCount();   //获取评论数量
    this.fetchpublishedNoteCount();   //获取收藏笔记数量
    this.checkIfCollected(); // 检查点赞状态
    this.checkIfCollectedNote();  //检查笔记收藏状态

  }  
};  
</script>  

<style scoped>  
#app {  
  max-width: 1500px; /* 整体最大宽度 */  
  margin: auto; /* 居中 */  
  padding: 20px;   
  display: flex; /* 使用Flexbox布局 */  
  justify-content: center; /*水平居中 */ 
  align-items: center; /* 垂直居中（确保外部容器高） */  
  min-height: 100vh; /* 设置最小高度为视口高度，实现垂直居中 */ 
}

.container {  
  display: flex; /* 使用Flexbox布局 */  
  flex-direction: row; /* 指定方向为行 */
  width: 100%; /* 宽度为100% */
  height: 100vh; /* 高度为视口高度 */
  margin-top: 90px;
}  

.left-panel {  
  flex: 3.5; /* 左侧内容区域占据2份 */  
  margin-right: 60px; /* 右侧与左侧的间距 */  
  margin-bottom: 30px; 
  overflow-y: auto; /* 垂直方向滚动 */
}  

.right-panel {  
  flex: 3; /* 右侧内容区域占据1份 */  
  border-left: 2px solid #ddd; /* 右侧边框 */  
  padding-left: 50px; /* 左侧内边距 */  
}  

.header {  
  display: flex;  
  align-items: center;  
  margin-bottom: 15px;  
}  

.note-header {  
  display: flex;  
  align-items: center;  
  margin-bottom: 10px;  
}  

.avatar {  
  border-radius: 50%;  
  width: 60px;  
  height: 60px;  
}  

.username {  
  margin-left: 10px;  
  font-size: 18px;  
  font-weight: bold;  
}  

.note-item {  
  margin-bottom: 20px;  
  padding: 20px;  
  border: 1px solid #ddd;  
  border-radius: 4px;  
  background-color: white;  
}  

.title {  
  font-size: 20px;  
  margin: 2px 0; 
  align-items: center; 
}  

.cover-image img {  
  width: 100%;  
  max-width: 300px;  
  height: auto;  
  border: 1px solid #ddd;  
  border-radius: 4px;  
}  

.content {  
  border: 1px solid lightblue;  
  padding: 10px;  
  min-height: 75px;  
  margin: 10px 0;  
  overflow-y: auto;  
  max-height: 300px;  
  word-wrap: break-word;  
  white-space: normal;  
  text-align: left;  
}  

.info-bar {  
  display: flex;  
  justify-content: space-between;  
  align-items: center;  
  margin-top: 5px;  
  color: gray;  
}  

.timestamp {  
  font-size: 12px;  
}  

.stats {  
  display: flex;  
  align-items: center;  
}  

.comments-container {  
  margin-top: 60px;  
  overflow-y: auto;  
  max-height: 400px;  
  border: 1px solid #ddd;  
  background-color: #f9f9f9;  
  padding: 20px;  
  border-radius: 4px;
  align-items: center;  
}  

.comment {  
  display: flex;  
  border-bottom: 2px solid #eaeaea;  
  align-items: center;  
  margin-bottom: 15px;  
}  

.comment-avatar {  
  border-radius: 60%;  
  width: 40px;  
  height: 40px;  
  margin-right: 10px;  
}  

.comment-info {  
  margin-left: 10px;  
  flex: 1;  
}  

.comment-header {  
  display: flex; /* 使用Flexbox布局 */  
  align-items: center; /* 垂直居中对齐 */  
  align-items: flex-start;
  width: 200px;  
}  
.comment-details {  
  margin-left: 4px; /* 与头像保持一定的间距 */  
}  

.comment-author {  
  font-weight: bold;  
}

.comment-date {  
  font-size: 12px;  
  color: gray;  
  margin-top: 5px;  
}  

.tag {  
  color: gray;  
  margin-left: 5px;  
}  

.comment-text {  
  word-wrap: break-word; /* 允许单词换行 */  
  white-space: normal; /* 允许正常换行 */  
  max-width: 34ch; /* 每行限制为20个字符宽 */ 
  text-align: left; /* 分页文本左对齐 */ 
  margin-top: 15px; 
  margin-bottom: 15px;
  margin-left: 10px;
}

.note-action {  
  margin-left: auto;  
  display: flex;  
  align-items: center;  
}  

.add-comment {  
  display: flex;  
  align-items: center; 
  width:100%; 
  margin-top: 10px; 
  justify-content: center; 
}  

.add-comment input {
  width: 100%; /* 减小宽度到60%，或者使用像素值，例如 'width: 400px;' */
  height: 100px; /* 增加高度，可以根据需要调整 */
  padding: 10px; /* 保持内边距，如果高度增加是通过增加padding实现的，可以忽略height属性 */
  margin-right: 10px;
  border: 1px solid #ddd;
  border-radius: 4px;
  resize: none; /* 禁止用户调整输入框大小 */
  
}

.add-comment button {
  display: inline-flex; /* 使用Flexbox布局，允许内部元素排列 */
  align-items: center; /* 垂直居中对齐内部元素 */
  justify-content: center; /* 水平居中对齐内部元素 */
  padding: 10px 15px; /* 调整按钮内边距 */
  color: rgb(30, 29, 29);
  border: none;
  border-radius: 4px;
  cursor: pointer;
  white-space: nowrap; /* 防止文本换行 */
  transition: background-color 0.3s; /* 添加背景色变化的过渡效果 */
}

.add-comment button:hover {  
  background-color: #3783d433;  
}  

.title-tag-container {  
  display: flex;  
  align-items: center;  
  margin-bottom: 10px;  
  justify-content: center;  
}  

.action-buttons {  
  display: flex;  
  align-items: center;  
}  
</style>
